import { Icon } from '@iconify/react'
import { Popup, TabBar } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'

import { CONST_ROUTES } from '@/constants'

import { TabbarItem } from './Tabbar.define'

const VISIBLE_PATHS = Object.values<string>(CONST_ROUTES)

export default function Tabbar() {
  const [visible, setVisible] = useState(false)
  const [tabs, setTabs] = useState<TabbarItem[]>([
    {
      key: CONST_ROUTES.INDEX,
      title: '首页',
      icon: <Icon icon="ant-design:home-outlined" />
    },
    {
      key: CONST_ROUTES.CATEGORY,
      title: '分类',
      icon: <Icon icon="ant-design:appstore-outlined" />
    },
    {
      key: CONST_ROUTES.SHOP,
      title: '商铺',
      icon: <Icon icon="ant-design:shop-outlined" />
    },
    {
      key: CONST_ROUTES.CART,
      title: '购物车',
      icon: <Icon icon="ant-design:shopping-outlined" />
    },
    {
      key: CONST_ROUTES.MY,
      title: '我的',
      icon: <Icon icon="ant-design:user-outlined" />
    }
  ])

  const navigate = useNavigate()
  const { pathname } = useLocation()

  function handleJump(path: string) {
    navigate(path)
  }

  useEffect(() => {
    const _visible = VISIBLE_PATHS.includes(pathname)

    setVisible(_visible)
  }, [pathname])

  return (
    <Popup visible={visible} mask={false} position="bottom">
      <TabBar activeKey={pathname} safeArea onChange={handleJump}>
        {tabs.map(tab => (
          <TabBar.Item
            key={tab.key}
            title={tab.title}
            icon={tab.icon}
          ></TabBar.Item>
        ))}
      </TabBar>
    </Popup>
  )
}
